package com.demo.mapsocial;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class LoginActivity extends Activity {

	private Button btnLogin;
	private AuthenticationSettings authSettings;
	private Facebook facebook = new Facebook("351456371607432");

	private static final String TAG = "Login";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				login();
			}
		});
	}

	private void login() {
		authSettings = new AuthenticationSettings(this);
		String token = authSettings.getAccessToken();
		long expires = authSettings.getAccessExpires();

		if (token != null && !token.isEmpty())
			facebook.setAccessToken(token);

		if (expires != 0)
			facebook.setAccessExpires(expires);

		if (!facebook.isSessionValid()) {
			facebook.authorize(this, new String[] { "email", "user_location",
					"user_about_me" }, new DialogListener() {

				public void onComplete(Bundle values) {
					Log.d(TAG, "onComplete - " + values.toString()
							+ " - INFO - " + values.getString("about"));

					authSettings.setAuthenticationInfo(
							facebook.getAccessToken(),
							facebook.getAccessExpires());
				}

				public void onFacebookError(FacebookError e) {
					Log.d(TAG, "onFacebookError - " + e.getMessage());
				}

				public void onError(DialogError e) {
					Log.d(TAG, "onError - " + e.getMessage());
				}

				public void onCancel() {
					Log.d(TAG, "onCancel");
				}

			});
		}
	}

	private void startMain() {
		// start the main application
		Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		facebook.authorizeCallback(requestCode, resultCode, data);
	}
}
